/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amit.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 *
 * @author amit
 */
public class WebAndFileUtils {

    /**
     * Looks through text for fromText, and then searches for the first instance of toText from there
     * It returns the text between the two, if fromText or toText cannot be found then it returns null
     * @param text
     * @param fromText
     * @param toText
     * @return
     */
    public static String parseTextFromString(String text, String fromText, String toText) {
        int length = fromText.length();
        int lIndex = text.indexOf(fromText);
        if (lIndex >= 0) {
            int rIndex = text.indexOf(toText, lIndex + length);
            if (rIndex >= 0) {
                text = new String(text.substring(lIndex + length, rIndex));
                return text;
            }
        }

        return null;
    }

    public static String getTextForURL(String url) throws IOException {
        BufferedReader bRead = new BufferedReader(new InputStreamReader((new URL(url)).openStream()));
        StringBuffer page = new StringBuffer();
        String line = null;
        while ((line = bRead.readLine()) != null) {
            page.append(line + "\n");
        }
        return page.toString();
    }

    public static String getTextForURLWithCookies(CookieManager c, String url) throws IOException {
        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        c.setCookies(conn);
        conn.setDoOutput(true);
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer response = new StringBuffer();
        String line = null;
        while ((line = rd.readLine()) != null) {
            response.append(line + "\n");
        }
        c.storeCookies(conn);
        rd.close();
        return response.toString();
    }

    public static String getPostParamsFromMap(HashMap<String, String> params) throws IOException {
        String data = "";
        for (String key : params.keySet()) {
            data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
        }
        return data;
    }

    public static String getTextForURLUsingPost(CookieManager c, String url, String postParams) throws IOException {
        // Construct data
        // Send data
        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        c.setCookies(conn);
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(postParams);
        wr.flush();
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer response = new StringBuffer();
        String line = null;
        while ((line = rd.readLine()) != null) {
            response.append(line + "\n");
        }
        c.storeCookies(conn);
        wr.close();
        rd.close();
        return response.toString();
    }

    public static String getTextForURLWithBasicAuth(String urlString, String theUsername, String thePassword) throws IOException {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        URL url = new URL(urlString);
        String authString = theUsername + ":" + thePassword;
        // Encode String
        String encoding = new sun.misc.BASE64Encoder().encode(authString.getBytes());

        // or
        // String encoding = Base64Converter.encode (userPassword.getBytes());

        // Need to work with URLConnection to set request property
        URLConnection uc = url.openConnection();
        uc.setRequestProperty("Authorization", "Basic " + encoding);
        InputStream content = (InputStream) uc.getInputStream();
        BufferedReader in =
                new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = in.readLine()) != null) {
            pw.println(line);
        }
        return sw.toString();
    }

    public static String readFile(String fileName) throws IOException {
        BufferedReader bRead = new BufferedReader(new FileReader(fileName));
        String line = null;
        String toReturn = "";
        while ((line = bRead.readLine()) != null) {
            toReturn += line;
        }
        return toReturn;
    }
}
